package com.example.springboot_demo.config;

import com.example.springboot_demo.controller.AlarmController;
import com.example.springboot_demo.model.OrderWms;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class WebSocketService {
    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
    private final ObjectMapper objectMapper = new ObjectMapper();  // 添加 ObjectMapper 实例
    private static final Logger logger = LoggerFactory.getLogger(WebSocketService.class);
    // 添加连接
    public void addSession(WebSocketSession session) {
        if (session == null) {
            throw new IllegalArgumentException("WebSocket session cannot be null");
        }
        sessions.put(session.getId(), session);
    }

    // 移除连接
    public void removeSession(WebSocketSession session) {
        if (session == null) {
            throw new IllegalArgumentException("WebSocket session cannot be null");
        }
        sessions.remove(session.getId());
    }

    // 获取所有会话
    public Collection<WebSocketSession> getSessions() {
        return sessions.values();
    }

    // 向所有客户端发送 JSON 格式的消息
    public void sendToClients(List<?> data, String type) {
        try {
            // 创建一个 Map 来表示 JSON 结构，type 由传入参数动态设置
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("type", type);  // 使用传入的 type 参数
            messageMap.put("data", data);  // 将任意类型的数据放入 'data' 字段

            // 将 Map 转换为 JSON 字符串
            String jsonMessage = objectMapper.writeValueAsString(messageMap);
            TextMessage message = new TextMessage(jsonMessage);  // 包装成 TextMessage

            for (WebSocketSession session : sessions.values()) {
                try {
                    if (session.isOpen()) {
                        session.sendMessage(message);  // 发送消息
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}